#include "stdafx.h"
#include "QtApp.h"
#include "launcher.h"

RayFrame::QtApp* RayFrame::g_qtApp = NULL;

RayFrame::QtApp::QtApp(void):
m_launcher(NULL), m_model(NULL), m_shader(NULL), m_texture(NULL)
{
  assert(!g_qtApp);
  g_qtApp = this;
}

RayFrame::QtApp::~QtApp(void)
{
  // notify we are going to delete qt app
  m_launcher->Enable(false);

  SAFE_DELETE(m_app);
}

void RayFrame::QtApp::Update( double timeElapsed )
{

}

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"

glm::mat4 LookGlm(RayFrame::Camera* camera)
{
  glm::vec3 pos;
  pos.x = camera->GetEye().x;
  pos.y = camera->GetEye().y;
  pos.z = camera->GetEye().z;

  glm::vec3 center;
  center.x = camera->GetCenter().x;
  center.y = camera->GetCenter().y;
  center.z = camera->GetCenter().z;

  glm::mat4 model = glm::lookAt(pos, center, glm::vec3(0,1,0));
  return model;
}

glm::mat4 PerspectiveGlm(RayFrame::Camera* camera)
{
  glm::mat4 pers = glm::perspective<float>(45.f, 1.f, 0.1f, 1000.f);
  return pers;
}

void RayFrame::QtApp::Render( double timeElapsed )
{
  RayFrame::g_renderer->SetClearColor(RayFrame::BLACK);

  if(!m_model)
  {
    m_model = MeshManager::InstanceRef().LoadObj("model1", "teapot.obj");
    m_shader = ShaderProgram::CreateFromFile("normal.glsl.vs", "normal.glsl.ps");
    m_texture = Texture::CreateFromFile("beaver_256.png");
  }
  g_renderer->Clear();
  g_App->GetCamera()->Look();
  
  m_shader->Begin();
  m_shader->SetShaderParam("ModelView", g_App->GetCamera()->GetMatrixModelView());
  m_shader->SetShaderParam("Projection", g_App->GetCamera()->GetMatrixProjection());
  m_shader->SetShaderParam("LightPosition", glm::vec3(10, 10, 10));
  m_shader->SetShaderParam("EyePosition", g_App->GetCamera()->GetEye());
  m_shader->BindImage("TexDiffuse", m_texture);

  m_model->Render(timeElapsed);
  DrawGrid();

  m_shader->End();
}

void RayFrame::QtApp::StartLoop()
{
  m_app->exec();
}

void RayFrame::QtApp::Exit()
{

}

void RayFrame::QtApp::OnClose()
{

}

void RayFrame::QtApp::InitApp()
{
  m_app = new QApplication(m_argc, m_argv);
  m_launcher = new Launcher();
  m_launcher->showMaximized();

  AppBase::InitApp();
}

RayFrame::FrameBase* RayFrame::QtApp::InitFrame()
{
  return m_launcher->GetFrame();
}


void RayFrame::QtApp::SetInitParams( int argc, char *argv[] )
{
  m_argc = argc;
  m_argv = argv;
}
